package com.yuhong.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuhong.reggie.common.R;
import com.yuhong.reggie.entity.Employee;
import com.yuhong.reggie.entity.Page;
import com.yuhong.reggie.exception.BusinessException;
import com.yuhong.reggie.mapper.EmployeeMapper;
import com.yuhong.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        Employee loginEmployee = employeeMapper.login(employee);

        if (loginEmployee ==null){
            return R.error("用户名或密码不存在");

        }
        String hex = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if(!loginEmployee.getPassword().equals(hex)){
            return R.error("密码错误");
        }
        if (loginEmployee.getStatus()==0){
            return R.error("用户被禁用了");
        }

        return R.success(loginEmployee);
    }

    /**
     * @param employee
     * @return true
     */
    @Override
    public boolean save(Employee employee) {
        Employee dblogin = employeeMapper.login(employee);

        if (dblogin!=null){
            throw new BusinessException("用户存在");
        }

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //状态
        employee.setStatus(1);
        //创建时间
        employee.setCreateTime(LocalDateTime.now());
        //修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //添加到数据库
        employeeMapper.save(employee);
        return true;

    }

    @Override
    public Page<Employee> findByPage(Integer Page, Integer PageSize, String name) {
        PageHelper.startPage(Page,PageSize);

        List<Employee> employeeList = employeeMapper.findByName(name);

        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        Page<Employee> objPage = new Page<>();
        objPage.setRecords(pageInfo.getList());
        objPage.setTotal(pageInfo.getTotal());
        return objPage;


    }

    /**
     * 修改状态
     *
     * @param employee
     * @return
     */
    @Override
    public boolean update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        return employeeMapper.update(employee)>0;
    }

    /**
     * 根据id
     *
     * @param id
     * @return
     */
    @Override
    public R<Employee> findById(Integer id) {
        Employee byId = employeeMapper.findById(id);
        return R.success(byId);
    }
}
